const app=getApp();

Page({
  data: {
    src:"/images/add_picture.png",
    selectItems:["从相册选取","拍照选取"],
    security:-1,//默认未添加图片。0-合规，1-违规，2审核中，-1未添加图片
    imgsize:100
  },
  selectorchange:function(e){
    var i=e.detail.value;
    var value=this.data.selectItems[i];
    this.setData({
      selector:value
    })
    var that=this
    if (this.data.selector=="从相册选取"){
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album'],
        //sizeType:['compressed'],
        async success(res) {
          console.log('文件路径：',res.tempFiles[0].tempFilePath)
          console.log('文件大小：',res.tempFiles[0].size/1024,'KB')
         // wx.setStorageSync('key',res.tempFiles[0].tempFilePath)
          that.setData({
            imgsize:Math.floor(res.tempFiles[0].size/1024),
            src:res.tempFiles[0].tempFilePath,
            security:2//每次导入图片默认未检测出
          })
          /*************原图预压缩开始******************* */
          var res_tempfile=await that.preZip(res.tempFiles[0].tempFilePath,200,200,40)
          console.log('预压缩图片地址',res_tempfile)
          /*************原图预压缩结束******************* */
          /********云函数安全检测开始*********/
          var res_security=await that.securityDetect(res_tempfile);
          that.setData({
            security:res_security
          })
          /********云函数安全检测开始*********/
        } 
      })
    }
    if (this.data.selector=="拍照选取"){
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['camera'],
       // sizeType:['compressed'],
        async success(res) {
          console.log('文件路径：',res.tempFiles[0].tempFilePath)
          console.log('文件大小：',res.tempFiles[0].size)
         // wx.setStorageSync('key',res.tempFiles[0].tempFilePath)
          that.setData({
            imgsize:Math.floor(res.tempFiles[0].size/1024),
            src:res.tempFiles[0].tempFilePath,
            security:2//每次导入图片默认未检测出
          })
         /*************原图预压缩开始******************* */
         var res_tempfile=await that.preZip(res.tempFiles[0].tempFilePath,200,200,40)
         console.log('预压缩图片地址',res_tempfile)
         /*************原图预压缩结束******************* */
         /********云函数安全检测开始*********/
         var res_security=await that.securityDetect(res_tempfile);
         that.setData({
           security:res_security
         })
         /********云函数安全检测结束*********/
              }
            });  
        }
    },
    onTapButton:function(e){
      var that=this;
      //console.log("内存中access_token为：",wx.getStorageSync('access_token'))
      if (that.data.security==0){//确认安全就跳转
        wx.showToast({
          title: '合规图片', //提示的内容
          duration: 2000, //持续的时间
          icon: 'success', //图标有success、error、loading、none四种
          mask: true //显示透明蒙层 防止触摸穿透
      })
      }
      else if (that.data.security==1){
        wx.showToast({
          title: '违规图片请重选', //提示的内容
          duration: 2000, //持续的时间
          icon: 'error', //图标有success、error、loading、none四种
          mask: true //显示透明蒙层 防止触摸穿透
      })
      }
      else if (that.data.security==2){
        wx.showToast({
          title: '安全审核请重试', //提示的内容
          duration: 2000, //持续的时间
          icon: 'loading', //图标有success、error、loading、none四种
          mask: true //显示透明蒙层 防止触摸穿透
      })
      }
      else if (that.data.security==-1){
        wx.showToast({
          title: '请点击添加图片', //提示的内容
          duration: 2000, //持续的时间
          icon: 'none', //图标有success、error、loading、none四种
          mask: true //显示透明蒙层 防止触摸穿透
      })
      }
    },
    compressimage:function(tempfile,quality){
      return new Promise((resolve, reject) => {
        wx.compressImage({
          src: tempfile, // 图片路径
          quality: quality ,// 压缩质量
          success(res){
            //console.log("缩放又压缩后临时文件地址",res.tempFilePath); // 生成临时文件路径
            resolve(res.tempFilePath);
           // console.log(res.tempFilePath)
            reject(tempfile);
          }
        });
      })
  
    },
    getfilesize:function(tempfile){
      return new Promise((resolve, reject) => {
        wx.getFileSystemManager().getFileInfo(
          {
            filePath:tempfile,
              success(res)
            {
              let imagesize=Math.ceil(res.size/1024);
              //console.log("getfileinfo ing..此时临时文件大小为",imagesize,"KB")
              resolve(imagesize)
            },
            fail(res){
              console.log("getfileinfo error",res)
            }
          })
      })
  
    },
    preZip:async function(tmp_src,tmp_imgprowidth,tmp_imgproheight,tmp_imgprosize){//依次为原图地址，期待宽度，期待高度，期待大小
      return new Promise((resolve, reject) => {
        console.log('***********图像预压缩开始*****************')
      var that=this;
      wx.getImageInfo({
        src: tmp_src,
        success: function (e2) {
          const imgW = e2.width;
          const imgH = e2.height;
          var dimgW = tmp_imgprowidth;
          var dimgH = tmp_imgproheight;
          const maxWidth=that.data.maxCanvasW;//设置最大分辨率
          const maxHeight=that.data.maxCanvasH;
          if (dimgW > maxWidth) {
            const ratio = maxWidth / dimgW
            dimgW = maxWidth
            dimgH = dimgH * ratio
        }
        if (dimgH > maxHeight) {
            const ratio = maxHeight / dimgH
            dimgW = dimgW * ratio
            dimgH = maxHeight
        }
  
         const dpr = wx.getSystemInfoSync().pixelRatio ;//影响清晰程度
  
          
         /* that.setData({//获取原图宽，高
            imgheight:e2.height,
            imgwidth:e2.width
          })*/
          const query = wx.createSelectorQuery();
          query.select('#avatarCanvas').fields({
                node: true,
                size: true
              }).exec(e3 => {
                console.log('获取画布：', e3);
                const canvas = e3[0].node;
                canvas.width=dimgW*dpr;
                canvas.height=dimgH*dpr;
                
                console.log("imgW,imgH:",imgW,imgH);
                console.log("dimgW,dimgH:",dimgW,dimgH);
                console.log("canvasW,canvasH:",canvas.width,canvas.height);
                
                const ctx = canvas.getContext('2d');
                ctx.scale(dpr,dpr);//按比例缩放
                ctx.clearRect(0, 0, dimgW,dimgH);//清空画布
                const img = canvas.createImage();//使用在线画布新建图像
                img.src=tmp_src;
  
                console.log("原图地址为",tmp_src)
                console.log("待加载图片为",img)
  
                img.onload = async () => 
                {
                  console.log('原图已加载完成，下一步将原图绘制在画布上');
     
                 ctx.drawImage(img, 0, 0,dimgW,dimgH);//将原图绘制在画布上
  
                  await new Promise(resolve => {
                    setTimeout(() => resolve(""), 50);
                  });
                  
                  wx.canvasToTempFilePath({
                    //offcanvas,//使用离线画布的内容保存临时文件
                    canvas,
                    x: 0,
                    y: 0,
                    destWidth: dimgW,
                    destHeight: dimgH,
                    fileType:"jpg",
                    quality:1,
                    async success(res) 
                    {
                           
                           //console.log("缩放后临时文件地址：",res.tempFilePath); 
                           let tempfile=res.tempFilePath;//原图
                           let tempfile1=tempfile;//压缩后的图，初始化为原图
                           let imagesize=await that.getfilesize(tempfile1)//初次测量原图
                          
                          console.log("要求文件大小为",tmp_imgprosize,"KB，此时临时文件大小为",imagesize,"KB")
                          let times=1
                          while (imagesize >tmp_imgprosize && times>0){
  
                            console.log("第",times,"次压缩:")
                            
                            tempfile1=await that.compressimage(tempfile,times);
                            times-=1
                          
                            imagesize=await that.getfilesize(tempfile1)
                            console.log("要求文件大小为",tmp_imgprosize,"KB，此时临时文件大小为",imagesize,"KB")
                            
                            }
  
                          console.log("最终图像地址为:",tempfile1)
                          
                         console.log('***********图像预压缩结束*****************')
                          resolve(tempfile1)
                          reject('SomthingWrong.jpg')
                        
                          }
                        })
                          
                     }
                  })
                }
                
  
              });
            })
            
        },
    TpreZip:async function(tmp_src,tmp_imgprowidth,tmp_imgproheight,tmp_imgprosize){//依次为原图地址，期待宽度，期待高度，期待大小
      return new Promise((resolve, reject) => {
        console.log('***********图像预压缩开始*****************')
        resolve(tmp_src)
        reject('SomthingWrong.jpg')
      })
            
        },
      
    securityDetect:async function(res_tempfile){//为原图地址
      return new Promise((resolve, reject) => {
        console.log('********云函数安全检测开始*********')
         var contentType="image/"+res_tempfile.split('.')[1];
         var that=this;
             
         //var contentType="image/jpg";
         const fsm = wx.getFileSystemManager();
              fsm.readFile({
                filePath:res_tempfile,//将预压缩图像喂给云函数做检测
                success: function (res) {
                  console.log('读取文件结果',res)
                  try{
                  wx.cloud.init({
                    env:'cloud-9ged6fbx14ed7c19'
                  });
                  console.log('初始化已完成，开始检测')
                  wx.cloud.callFunction({
                    name: 'checkImg2',
                    data: {
                      contentType: contentType,
                      arrayBuffer: res.data
                    },
                    success: function (res) {
                      var srcTips = "正在安全检测中"
                      
                      console.log('安全检测结果res.result:',res.result)
                      console.log('安全检测结果号res.result.errcode:',res.result.errCode)
                      if (res.result.errCode == 0) {
                        srcTips= "合法图片"
                        resolve(0)
   
                      } 
                      else {
                        srcTips= "违法图片"
                        resolve(1)
                      }
                      console.log("srcTips", srcTips)   
                      console.log('********云函数安全检测结束*********')                                   
                    },
                    fail: function (e) {
                      var srcTips= "检测接口异常，请再次提交";
                      resolve(2)
                      console.log("srcTips", srcTips)
                      wx.hideLoading()
                      console.log('********云函数安全检测结束*********')
                    }
                  })
                }catch(err){
                  console.log('imgSecCheck没执行')
                  reject(2)
                  console.log('********云函数安全检测结束*********')
                }
              }
            });  
        
             /********云函数安全检测结束*********/
      })
    }
});
